package com.mgq.netty.multiThreadServer;


import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.atomic.AtomicInteger;

import static com.mgq.netty.bytebuff.ByteBufferUtil.debugAll;

/**
 * 多线程版本server
 * <p>
 * boss线程负责处理accept,worker线程负责处理read事件
 */
@Slf4j
public class MultiThreadServer {

    public static void main(String[] args) throws IOException {
        Thread.currentThread().setName("boss");
        Selector boss = Selector.open();
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        ssc.bind(new InetSocketAddress(8080));
        ssc.register(boss, SelectionKey.OP_ACCEPT, null);
        //使用多个work来进行优化
        Worker[] workers = new Worker[Runtime.getRuntime().availableProcessors()];
        for (int i = 0; i < workers.length; i++) {
            workers[i] = new Worker("work-"+i);
        }
        AtomicInteger index = new AtomicInteger();
        while (true) {
            boss.select();
            Iterator<SelectionKey> iterator = boss.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();
                //处理accept事件
                if (key.isAcceptable()) {
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    log.debug("connected....{}", sc.getRemoteAddress());
                    //新的channel,关联到worker的selector,这样就分开处理了
                    log.debug("before register....{}", sc.getRemoteAddress());
                    //使用轮询算法
                    workers[index.getAndIncrement() % workers.length].init(sc);
                    //work-0线程中的selector.select()方法如果先执行,将会阻塞住,也就是说应该register,然后再select()
                    //否则select中没有注册事件,就会阻塞.
                    //正确的顺序是保证register在前执行,select在后面执行. 如果register在前,可以调用wakeup()方法
                    //但是此时,register在boss线程,select在work线程,无法控制住2个线程的执行顺序
                    //解决办法
                    // 让2个方法在同一线程中执行
                    //利用阻塞队列来进行解耦
                    log.debug("after register....{}", sc.getRemoteAddress());
                }
            }
        }
    }

    static class Worker implements Runnable {
        private Thread thread;
        private String name;
        private Selector selector;
        private volatile boolean start = false;
        private ConcurrentLinkedDeque<Runnable> queue = new ConcurrentLinkedDeque();
        /**
         * 提供构造方法
         *
         * @param name
         */
        public Worker(String name) {
            this.name = name;
        }

        /**
         * 初始化方法
         */
        public void init(SocketChannel sc) throws IOException {
            //使用start,线程只初始化一次,一个线程就可以处理多个channel
            if (!start) {
                thread = new Thread(this);
                thread.setName(this.name);
                selector = Selector.open();
                thread.start();
                start = true;
            }
            //此时,init()方法虽然还是在work中,但是调用还是boss线程调用
            //因此init()还是在boss线程执行. 我们应该想办法将这行代码加入到 selector.select()之前
            //两个线程之间传递数据,可以考虑使用队列来解耦
            //此时只是将任务放到了队列,而没有使用
            queue.add(()->{
                try {
                    sc.register(selector, SelectionKey.OP_READ, null);
                } catch (ClosedChannelException e) {
                    e.printStackTrace();
                }
            });
            selector.wakeup();//唤醒selector
        }

        @Override
        public void run() {
            while (true) {
                try {
                    //这,还是有可能取到空的.因为线程start后,队列内容还没有加进去,还是会阻塞到select()方法.正确应该是想办法唤醒selector,
                    //然后再把事件注册上.
                    /*Runnable task = queue.poll();
                    if (task != null) {
                        task.run();
                    }*/
                    selector.select();//work-0线程,这个方法会阻塞
                    Runnable task = queue.poll();
                    if (task != null) {
                        task.run();
                    }
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        iterator.remove();
                        if (key.isReadable()) {
                            ByteBuffer byteBuffer = ByteBuffer.allocate(16);
                            SocketChannel channel = (SocketChannel) key.channel();
                            channel.read(byteBuffer);
                            log.debug("thread name:"+this.name);
                            debugAll(byteBuffer);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
